package cn.exrick.search.service.bean;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;

/**
* @Description:   esTransportClientBeanFactory
* @Author:         shang
* @CreateDate:     2019/10/22 13:53
* @UpdateUser:     shang
* @UpdateDate:     2019/10/22 13:53
* @UpdateRemark:
* @Version:        1.0
*/
@Configuration
public class EsTransportClient {

    private static Logger logger = LoggerFactory.getLogger(EsTransportClient.class);
    @Autowired
    private EsConnection connection;

    @Bean(name = "transportClient")
    public TransportClient buildInit() throws Exception{
        Settings settings = Settings.builder()
                .put("cluster.name", connection.getClusterName()).build();
        try(TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName(connection.getConnectionIp()), connection.getConnectionPort()));){
            return client;
        }catch(Exception se){
            logger.error("can't create bean transportClient",se);
            throw new RuntimeException("can't create bean transportClient");
        }
    }
}
